<template>
  <el-dialog :title="isEdit? '修改学科' : '新增学科' " :visible="value" width="30%" @close="close">
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="学科名称" prop="subjectName">
    <el-input v-model.trim="ruleForm.subjectName"></el-input>
  </el-form-item>
  <el-form-item label="是否显示" prop="isFrontDisplay">
    <el-switch :active-value="1" :inactive-value="0" v-model="ruleForm.isFrontDisplay" inactive-color="#eb5851" active-color="#5ecb70"></el-switch>
  </el-form-item>
  <el-form-item :style="{ textAlign: 'right' }">
    <el-button @click="resetForm">取消</el-button>
    <el-button type="primary" @click="submitForm">{{ isEdit? '修改' : '更新' }}</el-button>
  </el-form-item>
  </el-form>
  </el-dialog>
</template>

<script>
import { addListRequest, updateSubRequest, update } from '../../api/hmmm/subjects'
export default {
  props: {
    isAddOrEdit: {
      type: String,
      required: true
    },
    id: {
      type: Number,
      required: true
    },
    value: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      // dialogFormVisible: false,
      ruleForm: {
        subjectName: '',
        isFrontDisplay: 0
      },
      rules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }]
      }
    }
  },
  computed: {
    isEdit () {
      return this.isAddOrEdit === 'edit'
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 关闭弹出来
    close () {
      this.$emit('input', false)
    },
    async init () {
      if (this.isAddOrEdit === 'edit') {
        const res = await updateSubRequest({ id: this.id })
        console.log(res)
        this.ruleForm.subjectName = res.data.subjectName
        this.ruleForm.isFrontDisplay = res.data.isFrontDisplay
      }
    },
    submitForm () {
      this.$refs.ruleForm.validate(async value => {
        console.log(value)
        if (value) {
          if (this.isAddOrEdit === 'edit') {
            console.log(111111)
            await update({ ...this.ruleForm, id: this.id })
            this.$message.success('修改成功')
          } else {
            await addListRequest(this.ruleForm)
            this.$message.success('添加成功')
          }
        }
        // 通知父组件修改然后刷新页面
        this.$emit('SUB_ADD')
        this.close()
        // 清空表单关闭表单
        // this.resetForm()
      })
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
      this.close()
    }
  }
}
</script>

<style scoped lang='less'></style>
